<template>
    <el-container>
        <el-main>
            <el-card class="box-card">
                <div slot="header" class="clearfix" style="padding-left: 0;">
                    <el-form ref="searchForm" class="searchForm" :model="searchForm" label-width="60px">
                        <el-row :gutter="15">
                            <el-col :span="4">
                                <el-form-item label="包含" label-width="40px">
                                    <el-input v-model="searchForm.searchValue" clearable
                                              @keyup.enter.native="getList()"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="20">
                                <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <!--<div class="buttons">-->
                    <!--<el-button type="primary" icon="fa fa-plus" @click="openDialog">新增</el-button>-->
                <!--</div>-->
                <div>
                    <tableTemplate ref="groupTableTemplate" :data="groupList" :options="tableOptions" @load="load"
                                   @handleSelectionChange="handleSelectionChange"
                                   @handleRowClick="handleRowClick"></tableTemplate>
                </div>
            </el-card>
            <el-dialog :title="groupDialogTitle" :visible.sync="groupDialogVisible" width="800px" height="100px">
                <el-form ref="groupForm" :rules="rules" :model="groupForm" label-width="100px" v-enterToNext>
                    <el-form-item label="单位名称" prop="name">
                        <el-input v-model="groupForm.name" autocomplete="off" placeholder="请输入单位名称"></el-input>
                    </el-form-item>
                    <el-form-item label="单位编号" prop="code">
                        <el-input v-model="groupForm.code" autocomplete="off" placeholder="请输入单位编号"></el-input>
                    </el-form-item>
                    <el-form-item label="单位类型" prop="org_type_sid">
                        <!--<v-tree-select :data="orgTypeTree" value-field-name="id"-->
                                       <!--:value="groupForm.org_type_sid" :showCheckbox="showCheckboxs"-->
                                       <!--default-expand-level="-1"-->
                                       <!--v-model="groupForm.org_type_sid"></v-tree-select>-->
                        <el-select value-field-name="id"  v-model="groupForm.org_type_sid" style="width:660px;">
                            <el-option
                                v-for="item in orgTypeTree"
                                :label="item.name"
                                :key="item.sid"
                                :value="item.sid">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="管理类型" prop="manage_type_sid">
                        <el-select value-field-name="id" v-model="groupForm.manage_type_sid" style="width:660px;">
                            <el-option
                                v-for="item in manageTypeOptions"
                                :label="item.display_text"
                                :key="item.sid"
                                :value="item.sid">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上传证件">
                        <el-checkbox v-model="groupForm.is_upload" :true-label="1"
                                     :false-label="0"></el-checkbox>
                    </el-form-item>
                    <el-form-item label="部位提醒">
                        <el-checkbox v-model="groupForm.is_part_remind" :true-label="1"
                                     :false-label="0"></el-checkbox>
                    </el-form-item>
                    <el-form-item v-if="groupForm.org_type_sid === '20'" label="必须首件">
                        <el-checkbox v-model="groupForm.sg_has_first" :true-label="1"
                                     :false-label="0"></el-checkbox>
                    </el-form-item>
                    <el-form-item label="上传图片" class="clearfix">
                        <el-upload class="uploadPicture"
                                   :action="fileApiUrl.uploadFile"
                                   :headers="{token: token,account_set_sid: account_set_sid }"
                                   list-type="picture-card"
                                   :file-list="$utils.isNotEmpty(groupForm.seal_sid) ? [{url: fileApiUrl.getFile+$utils.getAccountSetSid()+'/' + groupForm.seal_sid}] : []"
                                   :on-success="handleSealSuccess"
                                   :on-preview="handleSealPreview"
                                   :on-remove="handleSealRemove" style="float: left">
                            <i>上传印章</i>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="saveOrUpdateSysGroup" v-btnLoading>确 定</el-button>
                    <el-button @click="groupDialogVisible = false">取 消</el-button>
                </div>
            </el-dialog>

            <el-dialog title="查看印章" :visible.sync="sealDialogVisible">
                <img width="100%" :src="sealUrl" alt="">
            </el-dialog>
        </el-main>
    </el-container>
</template>

<script>
    import sysGroupApi from "@common/api/system/sysGroupApi";
    import sysRoleApi from '@common/api/system/sysRoleApi';
    import commonParameterValueApi from "@common/api/common/commonParameterValueApi";
    import sysUserApi from '@common/api/system/sysUserApi';
    import fileApi from "@common/api/fileApi";

    export default {
        name: "Group",
        data() {
            return {
                fileApiUrl: fileApi.url,
                token: this.$store.state.accessToken.token,
                account_set_sid:this.$utils.getAccountSetSid(),
                sealDialogVisible: false,
                sealUrl: '',
                searchForm: {},
                treeProps: {
                    children: 'children',
                    hasChildren: 'hasChildren'
                },
                groupList: [],
                listMap:{},
                tableOptions: {
                    ref: 'groupTable',
                    // multiSelect: true,
                    lazy: true,
                    rowKey: 'sid',
                    treeProps: {
                        children: 'children',
                        hasChildren: 'hasChildren'
                    },
                    columns: [
                        {
                            label: '单位名称',
                            prop: 'name',
                            width: 400,
                        },
                        {
                            label: '单位类型',
                            prop: 'org_name',
                            width: 150,
                            align: 'center',
                        },
                        {
                            label: '单位编号',
                            prop: 'code',
                            width: 90,
                            align: 'center',
                        },
                        {
                            label: '管理类型',
                            prop: 'display_text',
                            width: 100,
                            align: 'center',
                        },
                        {
                            label: '上传证件',
                            prop: 'is_upload',
                            width: 90,
                            align: 'center',
                            formatter: (row) => {
                                if (row.is_upload === 1) {
                                    return '是';
                                } else if (row.is_upload === 0) {
                                    return '否';
                                }
                                return '';
                            }
                        },
                        {
                            label: '部位提醒',
                            prop: 'is_part_remind',
                            width: 90,
                            align: 'center',
                            formatter: (row) => {
                                if (row.is_part_remind === 1) {
                                    return '是';
                                } else if (row.is_part_remind === 0) {
                                    return '否';
                                }
                                return '';
                            }
                        },
                    ],
                    operates: {
                        fixed: 'right',
                        width: 600,
                        list: [
                            {
                                label: '新增',
                                type: 'primary',
                                size: 'small',
                                icon: 'fa fa-plus',
                                show: true,
                                method: (index, row) => {
                                    this.openDialog(row);
                                }
                            },
                            {
                                label: '删除',
                                type: 'danger',
                                size: 'small',
                                icon: 'fa fa-trash-o',
                                show: true,
                                method: (index, row) => {
                                    this.deleteSysGroup(row);
                                }
                            },
                            {
                                label: '编辑',
                                type: 'primary',
                                size: 'small',
                                icon: 'fa fa-pencil',
                                show: true,
                                method: (index, row) => {
                                    this.editDialog(row);
                                }
                            },
                            {
                                label: '部门管理',
                                type: 'primary',
                                size: 'small',
                                show: true,
                                method: (index, row) => {
                                    this.deptManage(row);
                                }
                            },
                            {
                                label: '职务管理',
                                type: 'primary',
                                size: 'small',
                                show: true,
                                method: (index, row) => {
                                    this.jobManage(row);
                                }
                            },
                            {
                                label: '用户管理',
                                type: 'primary',
                                size: 'small',
                                show: true,
                                method: (index, row) => {
                                    this.userManage(row);
                                }
                            }
                        ],
                    },
                },
                groupDialogTitle: '',
                groupDialogVisible: false,
                rules: {
                    name: [{required: true, message: '请输入单位名称', trigger: 'blur'}],
                    code: [{required: true, message: '请输入单位编号', trigger: 'blur'}],
                    org_type_sid: [{required: true, message: '请选择单位类型', trigger: 'blur'}],
                    manage_type_sid: [{required: true, message: '请选择管理类型', trigger: 'blur'}],
                },
                groupForm: {},
                orgTypeTree: [],
                manageTypeOptions: [],
                showCheckboxs: true,
                selection: [],
                parentSid: '',
                currentParentSid: '',
                currentOrgSid: '',//当前登录用户单位sid

            };
        },
        mounted() {
            this.getCurrentLoginOrg();
            // this.getList();
            this.findOrgManageType();
            // this.initZTree();
        },
        methods: {
            load(data) {
                let item = this.listMap[data.tree.sid];
                data.resolve(item.children);
            },

            //获取单位管理类型参数
            findOrgManageType() {
                let params = {};
                params.key1 = 'org_manage_type';
                commonParameterValueApi.findCommonParameterValuesByKey(params, result => {
                    this.manageTypeOptions = result.data;
                })
            },

            //新增单位管理
            openDialog(row) {
                let $this = this;
                $this.parentSid = row.org_type_sid;
                $this.findOrtType();
                // this.initZTree();
                $this.groupForm = {group_type: 'org',sn: 1, state: 1,parent_sid: row.sid};
                $this.groupDialogTitle = '新增单位';
                if ($this.$refs['groupForm']) {
                    $this.$refs['groupForm'].clearValidate();
                }
                $this.groupDialogVisible = true;
            },

            //新增时获取单位类型
            findOrtType(){
                let $this = this;
                let queryData = {parent_sid:  $this.parentSid};
                baseOrgTypeApi.findBaseOrgTypeByParentSid(queryData,result =>{
                    $this.orgTypeTree = result.data;
                })
            },

            //编辑单位管理
            editDialog(row) {
                let $this = this;
                $this.orgTypeTree = [];
                $this.parentSid = row.org_type_sid;
                $this.findOrtTypeByEdit(row);
                $this.groupDialogTitle = '编辑';
                $this.groupForm = Object.assign({}, row);
                if ($this.$refs['groupForm']) {
                    $this.$refs['groupForm'].clearValidate();
                }
                $this.groupDialogVisible = true;
            },

            //修改时获取单位类型
            findOrtTypeByEdit(row){
                let $this = this;
                let queryData = {parent_sid:  row.org_parent_sid};
                baseOrgTypeApi.findBaseOrgTypeByParentSid(queryData,result =>{
                    $this.orgTypeTree = result.data;
                })
            },

            //获取当前登录用户的单位
            getCurrentLoginOrg() {
                let $this = this;
                let id = $this.$store.state.userInfo.id;
                let queryData = {id: id};
                sysUserApi.getSysUserParamsById(queryData, result => {
                    $this.currentSid = result.data.group_sid;
                    $this.currentParentSid = result.data.parent_sid;
                    $this.getList();
                });
            },


            getList() {
                let $this = this;
                let queryData = $this.searchForm;
                queryData.nopage = '1';
                queryData.group_type = 'org';
                $this.groupList = [];
                sysGroupApi.findSysGroupsParams(queryData, result => {
                    // $this.groupList = $this.procGroupData(result.data, '-1').concat([]);
                    $this.listMap={};
                    if (result.data && result.data.length>0){
                        // $this.$set($this.$data,"groupList",$this.procGroupData(result.data, result.data[0].parent_sid).concat([]));
                        $this.$set($this.$data,"groupList",$this.procGroupData(result.data, $this.currentParentSid).concat([]));
                        $this.$nextTick(function () {
                            $this.expandAll();
                        });
                    }
                });
            },

            expandAll() {
                let $this = this;
                let els = $('#app #baseTable-groupTable').find('.el-table__body-wrapper .el-table__expand-icon');
                if (els.length > 0) {
                    for (let i = 0; i < els.length; i ++) {
                        if ($(els[i]).hasClass('el-table__expand-icon--expanded')) {
                            continue;
                        }
                        els[i].click();
                        setTimeout(() => {
                            $this.expandAll();
                        }, 1);
                    }
                }
            },

            procGroupData(datas, parentSid) {
                let $this = this;
                let list = datas.filter(item => {
                    return item.parent_sid === parentSid;
                });
                list.forEach(item => {
                    item.children = $this.procGroupData(datas, item.sid);
                    item.hasChildren = item.children.length > 0;
                    $this.listMap[item.sid]=item;
                });
                return list;
            },

            handleRowClick(data) {
                // data.ref.toggleRowExpansion(data.row);
            },

            //表格复选框选中
            handleSelectionChange(val){
                this.selection = val;
            },

            //保存单位管理
            saveOrUpdateSysGroup() {
                let $this = this;
                $this.$refs['groupForm'].validate(valid => {
                    if (valid) {
                        sysGroupApi.saveSysGroup($this.groupForm, () => {
                            $this.groupDialogVisible = false;
                            $this.$message.success('保存成功！');
                            $this.getList();
                        });
                    } else {
                        return false;
                    }
                });
            },

            //印章上传成功
            handleSealSuccess(res) {
                this.groupForm = $.extend({}, this.groupForm, {
                    seal_sid: res.data.id,
                });
                this.isSeal = true;
            },
            //查看印章
            handleSealPreview(file) {
                if(file){
                    this.sealUrl = file.url;
                    this.sealDialogVisible = true;
                }
            },
            //删除印章
            handleSealRemove(file, fileList) {
                this.groupForm = $.extend({}, this.groupForm, {
                    seal_sid: '',
                });
            },

            //删除单位
            deleteSysGroup(row){
                let $this = this;
                $this.$confirm('是否删除该单位?', '温馨提示', {
                    cancelButtonClass: 'btn-custom-cancel',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let subData = {sids: [row.sid]};
                    sysGroupApi.deleteSysGroup(subData, () => {
                        $this.$message.success('删除成功！');
                        $this.getList();
                    });
                });
            },

            //部门管理
            deptManage(row) {
                this.$router.push({
                    path: '/group/dept',
                    query: {parent_sid: row.sid, parent_name: row.name,}
                });
            },

            //职务管理
            jobManage(row){
                this.$router.push({
                    path: '/group/duty',
                    query: {parent_sid: row.sid, parent_name: row.name,}
                });
            },

            //用户管理
            userManage(row){
                this.$router.push({
                    path: '/group/user/' + row.sid,
                });
            },
        },
    }
</script>

<style scoped>
    .box-card .searchForm .el-form-item--mini.el-form-item,
    .box-card .searchForm .el-form-item--small.el-form-item {
        margin-bottom: 0;
    }

    .buttons {
        margin: 0 0 10px 0;
    }
</style>
